package cn.jiyun.common;

import cn.jiyun.common.config.Result;
import cn.jiyun.pojo.Log;
import cn.jiyun.service.LogService;
import org.apache.http.client.utils.DateUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;

@Component
@Aspect
public class LogAspect {

    @Resource
    private LogService logService;

    @Around("@annotation(autoLogs)")
    public Object doAround(ProceedingJoinPoint joinPoint,AutoLogs autoLogs) throws Throwable{
        //操作内容
        String name = autoLogs.value();
        //操作时间
        LocalDateTime time = LocalDateTime.now();
        //操作人
        String operator = "admin";
        //操作人IP
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String address = request.getRemoteAddr();
        //操作类型
        Integer type = autoLogs.loggingtype();
        //操作路径
        String path = request.getRequestURL().toString();

        //执行接口操作
        Result result = (Result) joinPoint.proceed();

        //成功之后将数据插入数据库
        Log log = new Log(null, name, operator, address, type, path, time);
        System.out.println(log);
        logService.save(log);


        return result;
    }
}
